﻿// --------------------------------------------------------------------------------------------------------------------
// <summary>
//   Read a registry value as scripted without 'Windows on Windows' redirect.  IE Don't read from HKLM\Software\Wow3264node.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using Microsoft.Win32;
using Wolfpack.Core;

namespace Wolfpack.Contrib.Checks.Registry
{
    /// <summary>
    /// read/write registry keys
    /// </summary>
    public static class RegistryKeyExtension
    {
        /// <summary>
        /// To read a registry registryKey value.
        /// </summary>
        /// <param name="registryKey">
        /// The RegistryKey initialized to its base. Example RegistryKey.LocalMachine
        /// </param>
        /// <param name="subKeyString">
        /// The sub registryKey string. Example Software/Microsoft
        /// </param>
        /// <param name="keyName">
        /// The registry registryKey name.
        /// </param>
        /// <returns>
        /// The value of the registry registryKey.
        /// </returns>
        public static object GetSafeValue(this RegistryKey registryKey, string subKeyString, string keyName) 
        {
            RegistryKey registry = RegistryKey.FromHandle(registryKey.Handle, RegistryView.Registry64);
            RegistryKey subKey = registry.OpenSubKey(subKeyString, true);

            object value = null;
            if (subKey != null)
            {
                try
                {
                    value = subKey.GetValue(keyName);
                }
                catch (Exception e)
                {
                    Logger.Debug(string.Format("Error trying to read: {0} {1}, message is: {2}", 
                        subKey, keyName, e.Message));
                }
            }

            CloseDispose(new List<RegistryKey> { registry, subKey });
            return value;
        }

        /// <summary>
        /// Closes the Registry.
        /// </summary>
        /// <param name="registryKeys">
        /// The registry Keys.
        /// </param>
        public static void CloseDispose(List<RegistryKey> registryKeys)
        {
            foreach (var registryKey in registryKeys)
            {
                if (registryKey != null)
                {
                    registryKey.Close();
                    registryKey.Dispose();
                }
            }
        }
    }
}


